// request.ts
	import globalConfig from '@/js/globals';
interface RequestOptions {
  url: string;
  data?: any;
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  header?: Record<string, any>;
  timeout?: number; // 设置请求超时时间，单位为毫秒
}

interface ResponseData<T> {
  code: number;
  message: string;
  data: T;
}

class Request {
  private baseUrl: string = ''; // 默认基础 URL
  private defaultTimeout: number = 10000; // 默认超时时间，单位为毫秒
  private token: string = ''; // 保存 Token

  constructor(baseUrl: string) {
    this.baseUrl = baseUrl;
  }

  // 设置Token
  setToken(token: string) {
    this.token = token;
  }

  // GET 请求
  get<T>(url: string, data?: any, header?: Record<string, any>): Promise<ResponseData<T>> {
    return this.request<T>({ url, data, method: 'GET', header });
  }

  // POST 请求 (application/json)
  postJson<T>(url: string, data?: any, header?: Record<string, any>): Promise<ResponseData<T>> {
    const defaultHeader = {
      'Content-Type': 'application/json'
    };
    return this.request<T>({ url, data, method: 'POST', header: { ...defaultHeader, ...(header || {}) } });
  }

  // POST 请求 (multipart/form-data)
  postFormData<T>(url: string, data?: Record<string, any>, header?: Record<string, any>): Promise<ResponseData<T>> {
    const formData = this.convertToFormData(data);
    const defaultHeader = {
      'Content-Type': 'multipart/form-data'
    };
    return this.request<T>({ url, data: formData, method: 'POST', header: { ...defaultHeader, ...(header || {}) } });
  }

  // 统一的请求处理
  private request<T>(options: RequestOptions): Promise<ResponseData<T>> {
    return new Promise((resolve, reject) => {
      // 请求之前拦截：比如可以统一处理 token
      const headers = {
        ...(options.header || {})
      };
      if (this.token) {
        headers['Authorization'] = `Bearer ${this.token}`;
      }

      uni.request({
        url: this.baseUrl + options.url,
        method: options.method || 'GET',
        data: options.data || {},
        header: headers,
        timeout: options.timeout || this.defaultTimeout,
        success: (response) => {
          const data: ResponseData<T> = response.data as ResponseData<T>;
          if (data.code === 200) {
            resolve(data);
          } else {
            uni.showToast({
              title: data.message || '请求错误',
              icon: 'none'
            });
            reject(data);
          }
        },
        fail: (error) => {
          uni.showToast({
            title: '网络请求失败',
            icon: 'none'
          });
          reject(error);
        }
      });
    });
  }

  // 将对象转换为FormData格式
  private convertToFormData(data?: Record<string, any>): FormData {
    const formData = new FormData();
    if (data) {
      Object.keys(data).forEach((key) => {
        formData.append(key, data[key]);
      });
    }
    return formData;
  }
}

export default new Request(globalConfig.apiBaseUrl); // 将基础 URL 改为你的 API 地址
